#!/usr/bin/env python3
"""
Image Converter Script

This script converts images to PNG format and resizes them to 1/3 of their original height
while maintaining the aspect ratio.

Features:
- Converts various image formats (JPG, JPEG, BMP, TIFF, etc.) to PNG
- Resizes images to 1/3 of their original height (reducing by 1/3)
- Maintains aspect ratio during resizing
- Processes all images in a specified folder
- Saves converted images in a 'converted' subfolder

Requirements:
- Python 3.x
- Pillow library (pip install Pillow)
"""

import os
import sys
from PIL import Image

def convert_and_resize_images(input_folder):
    """
    Convert and resize images in the specified folder.
    
    Args:
        input_folder (str): Path to the folder containing images to process
    """
    # Check if the input folder exists
    if not os.path.exists(input_folder):
        print(f"Error: Folder '{input_folder}' does not exist.")
        return
    
    # Create output folder
    output_folder = os.path.join(input_folder, "converted")
    os.makedirs(output_folder, exist_ok=True)
    
    # Supported image formats
    image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.webp')
    
    # Count processed images
    processed_count = 0
    
    # Process each file in the input folder
    for filename in os.listdir(input_folder):
        if filename.lower().endswith(image_extensions):
            input_path = os.path.join(input_folder, filename)
            # Generate output filename with .png extension
            name_without_ext = os.path.splitext(filename)[0]
            output_filename = name_without_ext + '.png'
            output_path = os.path.join(output_folder, output_filename)
            
            try:
                # Open and process the image
                with Image.open(input_path) as img:
                    # Calculate new dimensions (1/3 of original height to reduce by 1/3)
                    new_height = int(img.height * 1 / 3)
                    new_width = int(img.width * (new_height / img.height))
                    
                    # Resize the image
                    resized_img = img.resize((new_width, new_height), Image.LANCZOS)
                    
                    # Save as PNG
                    resized_img.save(output_path, 'PNG')
                    print(f"Converted and resized: {filename} -> {output_filename}")
                    processed_count += 1
            
            except Exception as e:
                print(f"Error processing {filename}: {str(e)}")
    
    print(f"Processing complete. {processed_count} images processed.")
    print(f"Check the 'converted' folder inside '{input_folder}' for results.")

def show_help():
    """Display script usage information."""
    print(__doc__)

def get_folder_path():
    """Prompt user for folder path."""
    print("Image Converter Script")
    print("=" * 50)
    print("This script will:")
    print("1. Convert all images in a folder to PNG format")
    print("2. Resize them to 1/3 of their original height")
    print("3. Save them in a 'converted' subfolder")
    print()
    
    folder_path = input("Please enter the path to the folder containing images: ").strip()
    return folder_path

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help', 'help']:
        show_help()
        sys.exit(0)
    
    # Get folder path from user input
    folder_path = get_folder_path()
    
    if not folder_path:
        print("No folder path provided. Exiting.")
        sys.exit(1)
    
    convert_and_resize_images(folder_path)